import { HttpClient } from '@angular/common/http';
import { Reference } from '@angular/compiler/src/render3/r3_ast';
import { Component, OnInit, ɵɵqueryRefresh } from '@angular/core';
import { AbstractControl, FormBuilder, FormGroup } from '@angular/forms';
import { Observable } from 'rxjs';
import { User } from './uesr';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit{
  myForm: FormGroup;
  id: AbstractControl;
  userName: AbstractControl;
  password: AbstractControl;
  newpassword: AbstractControl;
  users$!: User[];

  baseUrl = 'http://127.0.0.1:/8080/user/'
  

  constructor(private fb: FormBuilder, private httpClient: HttpClient) {
    this.myForm = this.fb.group({
      'id':[''],
      'name':[''],
      'password':[''],
      'newpassword':['']
    });
    this.id = this.myForm.controls['id'];
    this.userName = this.myForm.controls['name'];
    this.password = this.myForm.controls['password'];
    this.newpassword = this.myForm.controls['newpassword'];
  }
  ngOnInit(): void {
    this.httpClient.get('http://127.0.0.1:8080/user/').subscribe(
      (res : any) => {
        this.users$ = res.data
      }
    )
  }

  look() {
    this.httpClient.get('http://127.0.0.1:8080/user/').subscribe(
      (res : any) => {
        this.users$ = res.data
      }
    )
  }

  add() {
    this.httpClient.post('http://127.0.0.1:8080/user/add',this.myForm.value).subscribe(
      (res : any) => {
        console.log(res)
        
        if(res["success"]==true)
        {this.look()
        alert("添加成功")}
        else alert("添加失败")
      }
    )
    
  }

  updata() {
    this.httpClient.post('http://127.0.0.1:8080/user/updata',this.myForm.value).subscribe(
      (res : any) => {
        console.log(res)
        if(res["success"]==true)
        {this.look()
        alert("修改成功")}
        else alert("修改失败")
      }
    )
  }

  delete() {
    this.httpClient.post('http://127.0.0.1:8080/user/delete',this.myForm.value).subscribe(
      (res : any) => {
        console.log(res)
        if(res["success"]==true)
        {this.look()
        alert("删除成功")}
        else alert("删除失败")
      }
    )
  }
}
